#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/epoll.h>

#include "ser.h"
#define _INT_BUF 1024
#define MAX_EVENTS 100

recv_cli_t user;
int grid[2] = {0};

extern unsigned int photo_size;

int count = 0;
int do_work(int arg);
int recv_msg(int fd,char *buf);
int main()
{
    struct epoll_event ev, events[MAX_EVENTS];
    int listen_sock, conn_sock, nfds, epollfd;

    listen_sock = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in saddr = {AF_INET};
    saddr.sin_port = htons(8888);
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    const char chOpt=1;
    setsockopt(listen_sock,IPPROTO_TCP,TCP_NODELAY,&chOpt,sizeof(char)); 

    int ret = bind(listen_sock,(struct sockaddr*)&saddr,sizeof(saddr));

    ret = listen(listen_sock,5);
    /*初始化epoll*/
    epollfd = epoll_create(100);
    if(epollfd == -1)
    {
        perror("epoll_create");
        close(listen_sock);
        return -1;
    }

    /*add listen_sock int epollfd*/
    ev.events = EPOLLIN;
    ev.data.fd = listen_sock;
    if(epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == -1)
    {
        perror("epoll_ctl:listen_sock");
        exit(EXIT_FAILURE);
    }

    while(1)
    {
        nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
        if(nfds == -1)
        {
            perror("epoll_pwait");
            exit(EXIT_FAILURE);
        }
        int n;
        for(n = 0; n < nfds; ++n)
        {
            if(events[n].data.fd == listen_sock)
            {
				struct sockaddr_in myclient;
				socklen_t len = sizeof myclient;
                conn_sock = accept(listen_sock, (struct sockaddr *)&myclient, &len);
                /*setnonblocking conn_sock*/
                int flags = fcntl(conn_sock, F_GETFL);
                if(flags < 0 || fcntl(conn_sock, F_SETFL, flags | O_NONBLOCK) < 0)
                {
                    puts("fcntl conn_sock nonblock error.");
                    break;
                }

                ev.events = EPOLLIN | EPOLLET;
                ev.data.fd = conn_sock;
                if(epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev) == -1)
                {
                    perror("epoll_ctl: conn_sock");
                    exit(EXIT_FAILURE);
                }
                puts("accept client success.");
            }
            else
            {
                /*recv and send*/
                do_work(events[n].data.fd);
            }
        }
    }
    /*close*/
    close(listen_sock);
    return 0;
}

int do_work(int arg)
{
    int fd = arg;
    char buf[_INT_BUF];
    int ret = -1;
    printf("do_work   count = %d\n", count);
    if(count == 0)
    {
        recv_msg(fd,buf);
        printf("%s\n",buf);
        memset(&user,0,sizeof(user));
        user= split(buf);

    }
    if(count == 1)
    {
        puts("------*******************------");
        unsigned int size = photo_size;
        char *info = (char *)malloc(size);
        memset(info,0,sizeof(size));
        recv_photo(fd, info);
        int boxnum = order_reg_auto();
        if(boxnum == -1)
        {
            return 0;
        }
        sprintf(buf,"%s#%s#%d\r\n",user.business,user.post,boxnum);
        send(fd, buf, strlen(buf),0);
        fflush(fdopen(fd,"r+"));
        printf("%s\n",buf);
        puts("------********-----*******------");
        count = 0;
        return 0;
    }
    int a = atoi(user.business);
    printf("a=%d\n",a);
    switch(a)
    {

        case 1:
            //登录
            ret = courier_log(user.phone,user.info);
            sprintf(buf,"%s#%s#%d\r\n",user.business,user.post,ret);
            ret = send(fd, buf, strlen(buf),0);
            fflush(fdopen(fd,"r+"));
            sleep(1);
            printf("%d-%s\n",ret,buf);
            break;

        case 2:
            //投递
            puts(user.phone);
            puts(user.info);
            ret = courier_send(user.phone,user.info);
            if(ret >= 0)
            {
                order_reg(ret);
            }

            else if(ret == -2)
            {
                count++;
                puts("---------------------------------------");
                printf("-----------------%d\n", count);

            }
            sprintf(buf,"%s#%s#%d\r\n",user.business,user.post,ret);
            send(fd, buf, strlen(buf),0);
            fflush(fdopen(fd,"r+"));
            printf("%s\n",buf);
            break;

        case 3:
            //取件
            ret = recv_package(user.phone,user.info);
            sprintf(buf,"%s#%s#%d\r\n",user.business,user.post,ret);
            send(fd, buf, strlen(buf),0);
            fflush(fdopen(fd,"r+"));
            printf("%s\n",buf);

    }

    close(fd);
    return 0;
}

int recv_msg(int fd,char *buf)
{
#if 0
    char* tp = buf;
    char c;
    while(1)
    {
        if(read(fd, &c, 1) <= 0) 
            break;
        if(c == '\r'){
            if(recv(fd, &c, 1, MSG_PEEK)>0 && c == '\n')
                read(fd, &c, 1);
            else
                *tp++ = '\n';
            break;
        }
        *tp++ = c;
    }
    *tp = '\0';
    puts(buf);
#endif
#if 1
    memset(buf,0,sizeof(buf));
    int i =0;
    i = recv(fd,buf,100,0);
    printf("%d--%s\n",i,buf);
#endif
    return 0;
}

int recv_photo(int fd,char *info)
{
    unsigned int size = photo_size;
    printf("size = %d\n", size);
    int i =0;
    int fdp = open("./qrcode.jpg", O_WRONLY | O_CREAT, 0644);
    unsigned int retur = 0;
    while(retur < size)
    {
        i = recv(fd,info,size,0);
        puts("hhhh  save_qrcode  hhhhhh");
        if(info[1] == '#')
        {
            puts(info);
        }
        else
        {
            unsigned int ret = write(fdp, info, i);

            retur += ret;

            printf("i = %d -- ret = %u --- retur = %u\n", i, ret, retur);
            puts("hhhh  save_qrcode  hhhhhh");
        }


    }
    close(fdp);
    puts("hhhh  fd  hhhhhh");
    return 0;
}




















